
/**
 * @Author: Kang
 * @Date: 2021/9/24 10:39
 * @Description: 跨域访问
 * @Version: 1.0
 */


package com.wanxi.education.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@Order(1)
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); // 允许任何的head头部
        //springboot 2.4.0以上
        corsConfiguration.addAllowedOrigin("http://hskdemo.natapp1.cc");//具体服务器
        corsConfiguration.addAllowedOrigin("https://www.hskdome.com");//具体服务器
        corsConfiguration.addAllowedOrigin("http://192.168.0.129:5500");
        corsConfiguration.addAllowedOrigin("http://localhost:8080");
        corsConfiguration.addAllowedOrigin("http://localhost:8081");
        corsConfiguration.addAllowedOrigin("http://localhost:8082");
        corsConfiguration.addAllowedOrigin("http://127.0.0.1:8080");
        corsConfiguration.addAllowedOrigin("http://192.168.56.1:5500");
        corsConfiguration.addAllowedOrigin("http://192.168.0.129:5500");

        //或者  corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedMethod("*"); // 允许任何的请求方法
        corsConfiguration.setAllowCredentials(true);

        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

